/*!
 * JQuery RatSplit pugin
 * Author:  Yotam Medini <yotam.medini@gmail.com> (GPL)
 *
 * Derived from: JQuery Spliter Plugin
 * Copyright (C) 2010 Jakub Jankiewicz <http://jcubic.pl> 
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License for more details.
 * 
 * You should have received a copy of the GNU Lesser General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
(function( $, undefined ) {
    var count = 0;
    var spliter_id = null;
    var spliters = [];
    var current_spliter = null;
    var methods = {
        init: function( options ) {
            function positions_set( p1_sz, split_sz, p2_sz ) {
                dim_func( panel_1, p1_sz );
                spliter.css( lefttop, split_sz );
                panel_2.css( lefttop, p1_sz + splitter_width );
                dim_func( panel_2, p2_sz );
            }
            function panel_set_style(panel) {
                panel.addClass("splitpart")
                    .css( 'overflow', "auto" );
            }
            var last_size = 0;
            var mouse_split_sizes = [1, 1];
            var settings = {
                is_vertical: false,
                splitter_width: 4,
                limit: 72
            };
            options && $.extend( settings, options );
            var is_vertical = settings.is_vertical;
            var splitter_width = settings.splitter_width;
            var dim_func = function( e, v ) {
                return is_vertical ? e.width( v ) : e.height( v ); 
            };
            var style_wh = function( e ) {
                if (dim_func(e) == 0) {
                    dim_func(e, splitter_width);                    
                }
            }
            var style_background = function( e ) {
                if ($(e).css( 'background-color' ) === 'rgba(0, 0, 0, 0)') {
                    $(e).css( 'background-color', "#f11");
                }
            }
            var set_default_style = function( e ) {
                if (dim_func(e) == 0) {
                    dim_func(e, splitter_width);                    
                }
                if ($(e).css( 'background-color' ) === 'rgba(0, 0, 0, 0)') {
                    $(e).css( 'background-color', "#666");
                }
            }

            var lefttop = is_vertical ? 'left' : 'top';
            var cls;
            var children = this.children();
            var panel_1 = children.first();
            var panel_2 = panel_1.next();
            $(panel_1).css( is_vertical ? 'top' : 'left', 0);
            // $(panel_2).css( is_vertical ? 'right' : 'bottom', 0);
            var dim100 = is_vertical ? 'height' : 'width';
            panel_set_style(panel_1);
            panel_set_style(panel_2);
            var width = this.width();
            var height = this.height();
            var id = count++;
            this.addClass( 'spliter_panel' );
            var cls = is_vertical ? 'vspliter' : 'hspliter';
            var spliter = $( '<div/>' ).addClass( cls )
                .css( 'position', 'absolute' )
//                .css( is_vertical ? 'width' : 'height', splitter_width)
                .css( 'overflow', 'auto' )
                .css( dim100, "100%" )
                .css( 'cursor', (is_vertical ? 'col' : 'row') + '-resize')
                .mouseenter( function() {
                spliter_id = id;
            } ).mouseleave( function() {
                spliter_id = null;
            } ).insertAfter( panel_1 );
            set_default_style( $(spliter) );
            var position;
            var self = $.extend( this, {
                position: ( function() {
                    return function( n ) 
                    {
                        if ( n === undefined ) {
                            return position;
                        } else {
                            position = n;
                            var sw = dim_func( spliter ) / 2;
                            var size = dim_func( self );
                            var p1_sz = n - sw;
                            var p2_sz = size - n - sw;
                            // We save these 'ideal' size
                            mouse_split_sizes = [p1_sz, p2_sz];
                            var $this = $( this );
                            positions_set( p1_sz, n - sw, p2_sz );
                        }
                    };
                } )(),
                is_vertical: settings.is_vertical,
                limit: settings.limit,
                destroy: function() {
                    spliter.unbind( 'mouseenter' );
                    spliter.unbind( 'mouseleave' );
                    self.unbind( 'spliter.resize' );
                    spliters[id] = null;
                    spliter.remove();
                    var not_null = false;
                    for ( var i = spliters.length; i--; ) {
                        if ( spliters[i] !== null ) {
                            not_null = true;
                            break;
                        }
                    }
                    //remove document events when no spliters
                    if ( !not_null ) {
                        $(document.documentElement ).bind( '.spliter' );
                        spliters = [];
                    }
                }
            } );

            self.bind( 'spliter.resize', function() {
               var size = dim_func( self );
               if ( last_size != size )
               {
                   last_size = size;
                   var spliter_size = dim_func( spliter );
                   size -= spliter_size; // what is left for 2 panels
                   var sw = spliter_size / 2;
                   var p1p2 = mouse_split_sizes; // abbrev.
                   var sum = Math.max( p1p2[0] + p1p2[1], 1 );
                   var p1_sz = Math.round( ( p1p2[0] * size ) / sum );
                   position = p1_sz + sw;
                   var p2_sz = size - p1_sz;
                   positions_set( p1_sz, position - sw, p2_sz );
               }
            } );


            //inital position of spliter
            this.width( width ).height( height ); // needed for %-settings.
            position = ( is_vertical ? width : height )/2;
            self.position( position );
            self.find( '.spliter_panel' ).trigger( 'spliter.resize' );

            if ( spliters.length === 0 ) { // first time bind events to document
                $(document.documentElement )
                    .bind( 'mousedown.spliter', function() {
                    if ( spliter_id !== null ) {
                        current_spliter = spliters[spliter_id];
                        $('<div class="splitterMask"></div>' )
                            .insertAfter( current_spliter );
                        $('body' ).css( 'cursor', 
                            (current_spliter.is_vertical ? 'col' : 'row' ) + 
                             '-resize' );
                        return false;
                    }
                } ).bind( 'mouseup.spliter', function() {
                    current_spliter = null;$('div.splitterMask' ).remove();
                    $('body' ).css( 'cursor', 'auto' );
                } ).bind( 'mousemove.spliter', function( e ) {
                    if ( current_spliter !== null ) {
                        var limit = current_spliter.limit;
                        var offset = current_spliter.offset();
                        var newpos = current_spliter.is_vertical ? 
                            e.pageX - offset.left : e.pageY - offset.top;
                        if ( newpos > current_spliter.limit &&
                            newpos < current_spliter.width()-limit ) {
                            current_spliter.position( newpos );
                            current_spliter.find( '.spliter_panel' )
                                .trigger( 'spliter.resize' );
                            return false;
                        }
                    }
                } );
            }
            spliters.push( self );
            return self;
        }
    };
    $.fn.ratsplit = function( method ) {
        if ( methods[method] ) {
            return methods[method].apply( this, 
                Array.prototype.slice.call( arguments, 1 ));
        } 
        else if ( typeof method === 'object' || !method ) {
            return methods.init.apply( this, arguments );
        } else {
            $.error( 'Method ' +  method + 
                ' does not exist on jQuery.ratsplit' );
        }    
    };
} )( jQuery );
